// 初始化浏览器历史记录和前进栈
let history = ['http://www.acm.org/']; // 假设初始页面是 http://www.acm.org/
let forwardStack = [];
// 处理用户输入的命令
function processCommand(command) {
if (command.startsWith("VISIT")) {
const url = command.substring(5).trim();
visit(url);
} else if (command === "BACK") {
back();
} else if (command === "FORWARD") {
forward();
} else if (command === "QUIT") {
return false; // 退出程序
} else {
console.log("Ignored");
}
return true;
}
// 访问新页面
function visit(url) {
if (history.length === 0 || history[history.length - 1] !== url) {
history.push(url);
forwardStack = []; // 清空前进栈
console.log(url);
}
}
// 后退到上一个页面
function back() {
if (history.length > 1) {
forwardStack.push(history.pop());
const currentUrl = history[history.length - 1];
console.log(currentUrl);
}
}
// 前进到下一个页面
function forward() {
if (forwardStack.length > 0) {
const url = forwardStack.pop();
history.push(url);
console.log(url);
}
}
// 读取用户输入并处理命令
function simulateNavigation(inputCommands) {
let i = 0;
while (i < inputCommands.length) {
const command = inputCommands[i].trim();
if (!processCommand(command)) {
break;
}
i++;
}
}
// 示例输入
const inputCommands = [
"VISIT http://acm.ashland.edu/",
"VISIT http://acm.baylor.edu/acmicpc/",
"BACK",
"BACK",
"FORWARD",
"VISIT http://www.ibm.com/",
"BACK",
"BACK",
"FORWARD",
"FORWARD",
"QUIT"
];
// 模拟导航
simulateNavigation(inputCommands);